#-*- coding: utf-8 -*-
#! /usr/bin/python

#######################################################################################
#                                                                                     #
#    File: online_keeper.py                                                           #
#    Part of 21tb_cheater                                                             #
#    Home: http://pcbeta-cheater.googlecode.com                                       #
#                                                                                     #
#    The MIT License                                                                  #
#                                                                                     #
#    Copyright (c) 2010-2011 <araya.akashic@gmail.com>                                #
#                                                                                     #
#    Permission is hereby granted, free of charge, to any person obtaining a copy     #
#    of this software and associated documentation files (the "Software"), to deal    #
#    in the Software without restriction, including without limitation the rights     #
#    to use, copy, modify, merge, publish, distribute, sublicense, and/or sell        #
#    copies of the Software, and to permit persons to whom the Software is            #
#    furnished to do so, subject to the following conditions:                         #
#                                                                                     #
#    The above copyright notice and this permission notice shall be included in       #
#    all copies or substantial portions of the Software.                              #
#                                                                                     #
#    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR       #
#    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,         #
#    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE      #
#    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER           #
#    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,    #
#    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN        #
#    THE SOFTWARE.                                                                    #
#                                                                                     #
#######################################################################################
# This code is to automatically do daily task for pcbeta bbs

# Author: elsesky

import time
import re

from PyQt4.QtCore import *
from PyQt4.QtGui import *

import urllib
import urllib2
import socket

from browser_bogus import Browser
from com_lib import *

account_list = {"":""}
cycle = 1
delay = 3610 * 22


try:
    _fromUtf8 = QString.fromUtf8
except AttributeError:
    _fromUtf8 = lambda s: s

#do not change below this if no need
user_agent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/13.0.772.0 Safari/535.1"

login_page_init = "http://nari.21tb.com/login/login.init.do?returnUrl=http%3A%2F%2Fnari.21tb.com%2Felos%2Fhtml%2Findex.init.do&elnScreen=1920*1200elnScreen"

login_page = "http://nari.21tb.com/login/login.checkLogin.do";
login_page2 = "http://nari.21tb.com/login/login.login.do";
logout_page = "http://nari.21tb.com/login/login.logout.do";

couse_list_post = "http://nari.21tb.com/els/html/course/course.listMyCourse.do"
couse_update_post = "http://nari.21tb.com/els/html/coursebasic/coursebasic.saveCoursePrecent.do"
goto_course_evaluate_pre = "http://nari.21tb.com/els/html/study/study.doStudy.do?linkBy=1&courseId="
course_evaluate = "http://nari.21tb.com/els/html/study/study.doStudy.do"



task_page = "http://i.pcbeta.com/home.php?mod=task";
task_doing_page = "http://i.pcbeta.com/home.php?mod=task&item=doing";
bangui_leaarn_pg1 = "http://bbs.pcbeta.com/viewthread-951045-7575-1.html";
post_bangui_learn_pg = "http://bbs.pcbeta.com/forum.php?mod=post&action=reply&extra=page%3D1&replysubmit=yes&infloat=yes&handlekey=fastpost&inajax=1";
bangui_ID = "75"
task_info_detail_pre = "http://i.pcbeta.com/home.php?mod=task&do=view&id="
bangui_learn_task_detail = "http://i.pcbeta.com/home.php?mod=task&do=view&id=" + bangui_ID
bangui_learn_need = False
defaulttimeout = 3

socket.setdefaulttimeout(defaulttimeout)

class ExamNotAvailable(Exception):
    def __init__(self, time):
        self.value = time
        
    def __str__(self):
        return repr(self.value)
    
class LoginFailed(Exception):
    def __init__(self, str):
        self.value = str
        
    def __str__(self):
        return repr(self.value)

#method login

def do_login(user):
    #记录日志调试
    fname = "sysrun.log"
    logd(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))+ "===========" + str("do login\r\n"))
#     try:
#         fp = open(fname, "a")
#         fp.write(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))+ "===========" + str("do login\r\n"))
#     except IOError:
#         print "log err"
    print "正在登录".decode("utf-8").encode('gbk')
    logd(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))+ "===========" + "正在登录".decode("utf-8").encode('gbk') + "\r\n")
    url = login_page_init
#First access,get COOKIE and store
    request = urllib2.Request(url)
    request.add_header("User-Agent", user.user_agent)
    clen = 0
    i = 1
    while clen < 20:
        try:
            result = user.urlOpener.open(request)
            logd(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))+ "===========" + "数据提交完毕".decode("utf-8").encode('gbk') + "\r\n")
            content = result.read();
            logd(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))+ "===========" + "读取内容完毕".decode("utf-8").encode('gbk') + "\r\n")
            clen = len(content)
            logd(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))+ "===========" + "内容长度为:".decode("utf-8").encode('gbk') + str(clen) + "\r\n")
            if i > 1:
                print '第'.decode('utf-8').encode('gbk') + str(i+1) +'次重试成功'.decode('utf-8').encode('gbk')
        except urllib2.URLError:
            print '第'.decode('utf-8').encode('gbk') + str(i+1) +'次重试失败'.decode('utf-8').encode('gbk')
            logd(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))+ "===========" + "休眠5秒后重试".decode("utf-8").encode('gbk') + "\r\n")
            time.sleep(5)
        except socket.timeout:
            print '第'.decode('utf-8').encode('gbk') + str(i+1) +'次重试失败'.decode('utf-8').encode('gbk')
            logd(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))+ "===========" + "休眠5秒后重试".decode("utf-8").encode('gbk') + "\r\n")
            time.sleep(5)
        i += 1
    logindata = {
                     "corpCode":"sgepri.com",
                     "referer":login_page_init,
                     "loginName":"0",
                     "loginName":user.username,
                     "password":user.password,
                     "submit.x":"52",
                     "submit.y":"8"
                }
    en_logindata = urllib.urlencode(logindata)
#init login post url login_page1只用来确认用户是否在其它地方登录过，无视即可
    url = login_page2;
    request = urllib2.Request(url, en_logindata)
    request.add_header("User-Agent", user.user_agent)
#do login
    clen = 0
    i = 1
#     fp.write(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))+ "===========" + str("do login post\r\n"))
    logd(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))+ "===========" + str("do login post\r\n"))
    while clen < 10:
        try:
            result = user.urlOpener.open(request)
            content = result.read()
            clen = len(content)
            
            if i > 1:
                print '第'.decode('utf-8').encode('gbk') + str(i+1) +'次重试成功'.decode('utf-8').encode('gbk')
        except urllib2.URLError:
            print '第'.decode('utf-8').encode('gbk') + str(i+1) +'次重试失败'.decode('utf-8').encode('gbk')
            logd(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))+ "===========" + "休眠5秒后重试".decode("utf-8").encode('gbk') + "\r\n")
            time.sleep(5)
        except socket.timeout:
            print '第'.decode('utf-8').encode('gbk') + str(i+1) +'次重试失败'.decode('utf-8').encode('gbk')
            logd(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))+ "===========" + "休眠5秒后重试".decode("utf-8").encode('gbk') + "\r\n")
            time.sleep(5)
        i += 1
    logd(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))+ "===========" + str("login post done\r\n"))
#check login
    if content.find("南瑞学堂".decode("utf-8").encode("gbk")) < 0:
        print "用户".decode('utf-8').encode('gbk') + user.username + "已成功登录".decode('utf-8').encode('gbk')
        logd(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))+ "===========" + "用户".decode('utf-8').encode('gbk') + user.username + "已成功登录\r\n".decode('utf-8').encode('gbk') + "\r\n")
#         fp.write(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))+ "===========" + str("login done\r\n"))
#         fp.close()
        return user;
    else:
        print "登录失败,请重试".decode('utf-8').encode('gbk')
        logd(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))+ "===========" + "登录失败,请重试".decode('utf-8').encode('gbk') + "\r\n")
#         fp.write(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))+ "===========" + str("login error\r\n"))
        logd(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))+ "===========" + str("login error\r\n"))
#         fp.close()
        raise LoginFailed(user.username)
        
#method completed task    
def get_couselist(user):
    print "获取课程列表".decode("utf-8").encode('gbk')
    logindata = {
                     "courseStatus":"NOT_STARTED,STUDY,HAS_EXPIRED",
                     "current_app_id":"",
                     "coureseStudyRecord":"",
                     "courseCodeOrName":"",
                     "objectId":"",
                     "objectType":"",
                     "courseStudyRecord.courseStudyType":"",
                     "page.pageNo":"1",
                     "page.pageSize":"5000",
                     "courseStudyType":""
                }
    en_logindata = urllib.urlencode(logindata)
    url = couse_list_post
    request = urllib2.Request(url, en_logindata)
    request.add_header("User-Agent", user.user_agent)
    clen = 0
    i = 1
    while clen < 10:
        try:
            result = user.urlOpener.open(request)
            content = result.read();
            clen = len(content)
            if i > 1:
                print '第'.decode('utf-8').encode('gbk') + str(i+1) +'次重试成功'.decode('utf-8').encode('gbk')
        except urllib2.URLError:
            print '第'.decode('utf-8').encode('gbk') + str(i+1) +'次重试失败'.decode('utf-8').encode('gbk')
            time.sleep(5)
        except socket.timeout:
            print '第'.decode('utf-8').encode('gbk') + str(i+1) +'次重试失败'.decode('utf-8').encode('gbk')
            time.sleep(5)
        i += 1
    couse_ids = []
    regex = re.compile(r'courseId":".*?"')
    for match in regex.findall(content):
#         print match.split("\":\"")[1].split("\"")[0]
        couse_ids.append(match.split("\":\"")[1].split("\"")[0]);
    return couse_ids
    
    
    
    
    
    
#   modify user refresh url

def update_lt(user,learnedtime="120"):
    couse_ids = get_couselist(user)
    for ids in couse_ids:
        print "更新课程ID:  ".decode("utf-8").encode('gbk') + ids
        logd(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))+ "===========" + "更新课程ID:  ".decode("utf-8").encode('gbk') + ids + "\r\n")
        logindata = {
                     "courseId":ids,
                     "playTime":learnedtime
                }
        en_logindata = urllib.urlencode(logindata)
        url = couse_update_post
        request = urllib2.Request(url, en_logindata)
        request.add_header("User-Agent", user.user_agent)
        clen = 0
        i = 1
        while clen < 10:
            try:
                result = user.urlOpener.open(request)
                content = result.read();
                clen = len(content)
                if i > 1:
                    print '第'.decode('utf-8').encode('gbk') + str(i+1) +'次重试成功'.decode('utf-8').encode('gbk')
                    time.sleep(2)
            except urllib2.URLError:
                print '第'.decode('utf-8').encode('gbk') + str(i+1) +'次重试失败'.decode('utf-8').encode('gbk')
                time.sleep(5)
            except socket.timeout:
                print '第'.decode('utf-8').encode('gbk') + str(i+1) +'次重试失败'.decode('utf-8').encode('gbk')
                time.sleep(5)
            i += 1
            if clen == 0:
                update_lt_evaluate(user,ids)
                clen = 9999
        #如果有已经完成的课程，执行进入考试步骤
        if content.find("\"100\"")> 0:
            update_lt_evaluate(user,ids)
#             print content

def update_lt_evaluate(user , cid):
    #检查该课程的状态
    step_stat = get_course_status(user,cid)
    #如果该课程为已经提交评价，并进入考试进程时，不再提交评价
    if step_stat == "COURSE_EXAM":
        print "ID为".decode("utf-8").encode('gbk') + cid + "的课程已评价过，需考试，跳过".decode("utf-8").encode('gbk')
        logd(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))+ "===========" + "ID为".decode("utf-8").encode('gbk') + cid + "的课程已评价过，需考试，跳过".decode("utf-8").encode('gbk') + "\r\n")
        return
    
    print "完成课程ID".decode("utf-8").encode('gbk') + cid + "的学习，尝试评价该课程".decode("utf-8").encode('gbk')
    logd(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))+ "===========" + "完成课程ID".decode("utf-8").encode('gbk') + cid + "的学习，尝试评价该课程".decode("utf-8").encode('gbk') + "\r\n")
    url = goto_course_evaluate_pre + cid
    logindata = {
                 "Referer":"http://nari.21tb.com/els/html/course/course.frame.do"
            }
    en_logindata = urllib.urlencode(logindata)
    request = urllib2.Request(url, en_logindata)
    request.add_header("User-Agent", user.user_agent)
    clen = 0
    i = 1
    while clen < 10:
        try:
            result = user.urlOpener.open(request)
            content = result.read();
            clen = len(content)
            if i > 1:
                print '第'.decode('utf-8').encode('gbk') + str(i+1) +'次重试成功'.decode('utf-8').encode('gbk')
        except urllib2.URLError:
            print '第'.decode('utf-8').encode('gbk') + str(i+1) +'次重试失败'.decode('utf-8').encode('gbk')
            time.sleep(5)
        except socket.timeout:
            print '第'.decode('utf-8').encode('gbk') + str(i+1) +'次重试失败'.decode('utf-8').encode('gbk')
            time.sleep(5)
        i += 1
        if clen == 0:
            break
#     print content
    url = course_evaluate
    logindata = {
                 "type":"COURSE_EVALUATE_SAVE",
                 "answers":"[{\"name\":\"4df9b0b2e0e14869a185fc024a6cdeec\",\"value\":\"\"},{\"name\":\"5159dba01a664fb79b8f0ad547165259\",\"value\":\"\"},{\"name\":\"ab10aa493b6a4f3e9b8ce36804ec6a25\",\"value\":\"\"}]",
                 "courseId":cid,
                 "star":"5",
                 "current_app_id":""
            }
    en_logindata = urllib.urlencode(logindata)
    request = urllib2.Request(url, en_logindata)
    request.add_header("User-Agent", user.user_agent)
    clen = 0
    i = 1
    while clen < 10:
        try:
            result = user.urlOpener.open(request)
            content = result.read();
            clen = len(content)
            if i > 1:
                print '第'.decode('utf-8').encode('gbk') + str(i+1) +'次重试成功'.decode('utf-8').encode('gbk')
        except urllib2.URLError:
            print '第'.decode('utf-8').encode('gbk') + str(i+1) +'次重试失败'.decode('utf-8').encode('gbk')
            time.sleep(5)
        except socket.timeout:
            print '第'.decode('utf-8').encode('gbk') + str(i+1) +'次重试失败'.decode('utf-8').encode('gbk')
            time.sleep(5)
        i += 1
        if clen == 0:
            break
#     print content
#     exit()

#获取课程 
def get_course_status(user,cid):
    #获取课程编号后获取该课程的ID
    curl = "http://nari.21tb.com/els/html/course/course.courseInfo.do?courseId=" + cid
    ccontent = getcontent(curl,user)
    regex = re.compile(r'(课程编号：.*?)<\/')
    match = regex.findall(ccontent)
    courseid = match[0].split("课程编号：")[1].split(")")[0]
#     print courseid

    #通过ID获取该课程的详细信息
    curl = "http://nari.21tb.com/els/html/course/course.listMyCourse.do"
    logindata = {
                 "coureseStudyRecord":"",
                 "courseCodeOrName":courseid,
                 "courseStatus":"",
                 "courseStudyType":"",
                 "current_app_id":"",
                 "objectId":"",
                 "objectType":"",
                 "page.pageNo":"1",
                 "page.pageSize":"1",
                 "selectStudyClient":"",
            }
    course_des = getpostcontent(curl,user,logindata)
#     print course_des
    regex = re.compile(r'\"currentStep\":\".*?\",')
    match = regex.findall(course_des)
    step_stat = match[0].split("\"currentStep\":\"")[1].split("\"")[0]
#     print step_stat
    return step_stat


def logout(user):
     url = logout_page
     request = urllib2.Request(url)
     request.add_header("User-Agent", user.user_agent)
     clen = 0
     i = 1
     while clen < 100:
        try:
            result = user.urlOpener.open(request)
            content = result.read();
            clen = len(content)
            if i > 1:
                print '第'.decode('utf-8').encode('gbk') + str(i+1) +'次重试成功'.decode('utf-8').encode('gbk')
        except urllib2.URLError:
            print '第'.decode('utf-8').encode('gbk') + str(i+1) +'次重试失败'.decode('utf-8').encode('gbk')
            time.sleep(5)
        except socket.timeout:
            print '第'.decode('utf-8').encode('gbk') + str(i+1) +'次重试失败'.decode('utf-8').encode('gbk')
            time.sleep(5)
        i += 1
     print "Online Keeper Logout " + user.username
     logd(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))+ "===========" + "Online Keeper Logout. username: " + user.username + "\r\n")

def select_lession(user,lessionnum=2):
    fname = "cp.log"
    cnum = 0
    totalpg = 250
    cp = 1
    #读取记录文件中的页数
    try:
        fp = open(fname, "r")
        cp = int(_fromUtf8(fp.read()))
    except IOError:
        cp = 1
    
    if cp>totalpg or cp<1:
        cp=1
    
    
    while cp<totalpg:
        print "===========正在刷第".decode('utf-8').encode('gbk') + str(cp) + "页===========".decode('utf-8').encode('gbk')
        logd(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))+ "===========正在刷第".decode('utf-8').encode('gbk') + str(cp) + "页\r\n".decode('utf-8').encode('gbk') + "\r\n")
        logindata = {
                         "courseInfo.categoryId":"",
                         "courseInfo.terminal":"",
                         "objectId":"",
                         "objectName":"",
                         "courseLimitType":"NEW",
                         "type":"UNCHECKED",
                         "current_app_id":"",
                         "page.pageNo":cp,
                    }
        en_logindata = urllib.urlencode(logindata)
        url = 'http://nari.21tb.com/els/html/elective/elective.courseInfoList.do'
        request = urllib2.Request(url, en_logindata)
        request.add_header("User-Agent", user.user_agent)
        clen = 0
        i = 1
        while clen < 10:
            try:
                result = user.urlOpener.open(request)
                content = result.read();
                clen = len(content)
                
                #检查是否已经超时，如果超时，重新登录后再次刷新该页
                if content.find("top.location.href=\"\/login\/login.init.do")>0:
                    print '用户SESSION已超时，重登录'.decode('utf-8').encode('gbk')
                    logd(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))+ "用户SESSION已超时，重登录".decode('utf-8').encode('gbk') + "\r\n")
                    #重登录
                    logout(user)
                    do_login(user)
                    continue
                
                if i > 1:
                    print '第'.decode('utf-8').encode('gbk') + str(i+1) +'次重试成功'.decode('utf-8').encode('gbk')
            except urllib2.URLError:
                print '第'.decode('utf-8').encode('gbk') + str(i+1) +'次重试失败'.decode('utf-8').encode('gbk')
                time.sleep(5)
            except socket.timeout:
                print '第'.decode('utf-8').encode('gbk') + str(i+1) +'次重试失败'.decode('utf-8').encode('gbk')
                time.sleep(5)
            i += 1
        couse_ids = []
        regex = re.compile(r'data-id=\".*?" data-type')
        for match in regex.findall(content):
            cid = match.split("\"")[1].split("\"")[0]
            curl = "http://nari.21tb.com/els/html/course/course.courseInfo.do?courseId=" + cid
            ccontent = getcontent(curl,user)
            if ccontent.find("课程评估")>0:
                #if the lession total selected more than the limit setting, return.
                if cnum >= lessionnum:
                    #写入当前读取的页数
                    fp = open(fname,"w")
                    #因为已经选过的在翻页后导致后面的课程前移，需要减去选的课程数除以每页的课程数
                    fp.write(str(cp-int(lessionnum/10)))
                    fp.close()
                    return
#                 print cid
                getlession('http://nari.21tb.com/els/html/elective/elective.chooseCourseOrCoursePack.do',user,cid)
                cnum += 1
                print '已选课程ID'.decode('utf-8').encode('gbk') + str(cid)
                logd(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))+ "===========" + '已选课程ID'.decode('utf-8').encode('gbk') + str(cid) + "\r\n")
#                 continue
#             return

        cp +=1
        fp = open(fname,"w")
        fp.write(str(cp))
        fp.close()
        logd(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))+ "===========" + '选课完毕'.decode('utf-8').encode('gbk') + str(cnum) + "\r\n\r\n")
        
        
def select_lession_by_credit  (user,creditnum=2):
    fname = "cp_credit.log"
    #由于学分有小数，转换为浮点计算
    creditnum = float(creditnum)
    cnum = 0.0
    totalpg = 250
    cp = 1
    #读取记录文件中的页数
    try:
        fp = open(fname, "r")
        cp = int(_fromUtf8(fp.read()))
    except IOError:
        cp = 1
    
    if cp>totalpg or cp<1:
        cp=1
    
    
    while cp<totalpg:
        print "===========正在刷第".decode('utf-8').encode('gbk') + str(cp) + "页===========".decode('utf-8').encode('gbk')
        logd(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))+ "===========正在刷第".decode('utf-8').encode('gbk') + str(cp) + "页\r\n".decode('utf-8').encode('gbk'))
        logindata = {
                         "courseInfo.categoryId":"",
                         "courseInfo.terminal":"",
                         "objectId":"",
                         "objectName":"",
                         "courseLimitType":"NEW",
                         "type":"UNCHECKED",
                         "current_app_id":"",
                         "page.pageNo":cp,
                    }
        en_logindata = urllib.urlencode(logindata)
        url = 'http://nari.21tb.com/els/html/elective/elective.courseInfoList.do'
        request = urllib2.Request(url, en_logindata)
        request.add_header("User-Agent", user.user_agent)
        clen = 0
        i = 1
        while clen < 10:
            try:
                result = user.urlOpener.open(request)
                content = result.read();
                clen = len(content)
                
#                 print '当前页内容大小'.decode('utf-8').encode('gbk') + str(clen)
#                 logd(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))+ "===========当前页内容大小".decode('utf-8').encode('gbk') + str(clen) + "\r\n")
#                 debug
#                 fnamet = str(cp) +  ".htm"
#                 fpt = open(fnamet, "w")
#                 fpt.write(content)
#                 fpt.close()

                #检查是否已经超时，如果超时，重新登录后再次刷新该页
                if content.find("top.location.href=\"\/login\/login.init.do")>0:
                    print '用户SESSION已超时，重登录'.decode('utf-8').encode('gbk')
                    logd(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))+ "用户SESSION已超时，重登录".decode('utf-8').encode('gbk') + "\r\n")
                    #重登录
                    logout(user)
                    do_login(user)
                    continue
                
                if i > 1:
                    print '第'.decode('utf-8').encode('gbk') + str(i+1) +'次重试成功'.decode('utf-8').encode('gbk')
            except urllib2.URLError:
                print '第'.decode('utf-8').encode('gbk') + str(i+1) +'次重试失败'.decode('utf-8').encode('gbk')
                time.sleep(5)
            except socket.timeout:
                print '第'.decode('utf-8').encode('gbk') + str(i+1) +'次重试失败'.decode('utf-8').encode('gbk')
                time.sleep(5)
            i += 1
        creditnums = []
        #学分下标
        cindex = 0
        cregex = re.compile(r'学分：</span><span class=\"orange\">.*?</span>')
        for cmatch in cregex.findall(content):
#             print cmatch.split("orange\">")[1].split("<")[0]
            creditnums.append(float(cmatch.split("orange\">")[1].split("<")[0]))
        #搜索课程，注意匹配学分下标        
        regex = re.compile(r'data-id=\".*?" data-type')
        for match in regex.findall(content):
            
            cid = match.split("\"")[1].split("\"")[0]
            curl = "http://nari.21tb.com/els/html/course/course.courseInfo.do?courseId=" + cid
            ccontent = getcontent(curl,user)
            
            
            if ccontent.find("课程评估")>0:
                #if the lession total selected more than the limit setting, return.
                if cnum >= creditnum:
                    #写入当前读取的页数
                    fp = open(fname,"w")
                    fp.write(str(cp))
                    fp.close()
                    return
#                 print cid
                getlession('http://nari.21tb.com/els/html/elective/elective.chooseCourseOrCoursePack.do',user,cid)
                #累加已经选择的课程的学分
                cnum += creditnums[cindex]
                print '已选课程ID'.decode('utf-8').encode('gbk') + str(cid)
                logd(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))+ "===========" + '已选课程ID'.decode('utf-8').encode('gbk') + str(cid) + "\r\n")
                print '当前已选学分'.decode('utf-8').encode('gbk') + str(cnum)
                logd(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))+ "===========" + '当前已选学分'.decode('utf-8').encode('gbk') + str(cnum) + "\r\n")
            #课程下标顺移
            cindex += 1
        cp +=1
        fp = open(fname,"w")
        fp.write(str(cp))
        fp.close()
        logd(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))+ "===========" + '选课完毕'.decode('utf-8').encode('gbk') + str(cnum) + "\r\n\r\n")

def getlession(url,user,lid):
    
#     print "in getlession"
    
    logindata = {
                     "endStudyTime":"2024-01-16",
                     "startStudyTime":"2014-01-16",
                     "objId":lid,
                     "objType":"COURSE",
                     "current_app_id":"",
                }
    en_logindata = urllib.urlencode(logindata)
    url = 'http://nari.21tb.com/els/html/elective/elective.chooseCourseOrCoursePack.do'
    request = urllib2.Request(url, en_logindata)
    request.add_header("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
    request.add_header("X-Requested-With", "XMLHttpRequest")
    request.add_header("Referer", "http://nari.21tb.com/els/html/course/course.frame.do")
    request.add_header("Accept-Language", "en-US,en;q=0.8,zh-Hans-CN;q=0.6,zh-Hans;q=0.4,ja;q=0.2")
    request.add_header("Origin", "http://nari.21tb.com")
    request.add_header("Accept-Encoding", "gzip, deflate")
    request.add_header("User-Agent", user.user_agent)
    
    try:
        result = user.urlOpener.open(request)
        content = result.read();
        clen = len(content)
        print '第'.decode('utf-8').encode('gbk') + str(1) +'次提交成功'.decode('utf-8').encode('gbk')
    except urllib2.URLError:
        print '第'.decode('utf-8').encode('gbk') + str(1) +'次提交失败'.decode('utf-8').encode('gbk')
        time.sleep(5)
    except socket.timeout:
        print '第'.decode('utf-8').encode('gbk') + str(1) +'次提交失败'.decode('utf-8').encode('gbk')
        time.sleep(5)


   
    
if __name__ == "__main__":
    while cycle:
        print "------------------------------------------"
        print time.strftime("%a, %b %d %Y %H:%M:%S", time.localtime()) + "-----------------"
        user = Browser('55109', "", user_agent)
        do_login(user)
        update_lt(user)
        logout(user)
        if cycle > 1:
            time.sleep(delay)
        cycle = cycle - 1